Page({
  data: {
    mqtt: {
      uid: 'c7e9d9637de217b40bae8d1afd279e31',
      url_push: 'https://api.bemfa.com/api/device/v1/data/3/push/get/',
      topic_cmd: 'WCtoESP',
      topic_log: 'LOG'
    },
    input: {
      name: undefined,
      id: undefined,
      password: undefined,
      passwordCheck: undefined,
      time_start: "00:00",
      time_end: "00:00"
    },
    userInfo: [],
    userRequest: [],
    userRequestReply: [],
    isLogin: false
  },
  mqttSend: function(topic, msg) {
    let that = this
    wx.request({
      url: that.data.mqtt.url_push,
      data: {
        uid: that.data.mqtt.uid,
        topic: topic,
        msg: msg
      },
      success(res) {
        console.log('[manager] 向Topic[' + topic + ']推送消息:')
        console.log(res)
      },
      fail() {
        console.log('[manager] HTTPS请求失败！')
      }
    })
  },
  checkUserRequest: function() {
    while(this.data.userRequest.length != 0) {
      let user = this.data.userRequest.pop()
      let that = this
      wx.showModal({
        title: '访问申请',
        content: '用户 [' + user.name + '(id:' + user.id + ')] 申请于时间段 [' + user.time_start + '-' + user.time_end + '] 内访问',
        cancelText: '拒绝',
        confirmText: '允许',
        success: function (res) {
          if (res.confirm) {
            that.mqttSend(that.data.mqtt.topic_cmd, {
              cmd: "set_id_time",
              id: user.id,
              sh: parseInt(user.time_start.slice(0, 2)),
              sm: parseInt(user.time_start.slice(3, 5)),
              eh: parseInt(user.time_end.slice(0, 2)),
              em: parseInt(user.time_end.slice(3, 5))
            })
            that.data.userInfo.find(item => item.id == user.id).time_start = user.time_start
            that.data.userInfo.find(item => item.id == user.id).time_end = user.time_end
            that.setData({userInfo: that.data.userInfo})
            that.data.userRequestReply.push({
              id: user.id,
              time_start: user.time_start,
              time_end: user.time_end,
              reply: true
            })
            var userChange = that.data.userInfo.find(item => item.id === user.id)
            that.data.userInfo.splice(that.data.userInfo.findIndex(item => item.id === user.id), 1)
            that.data.userInfo.push({
              id: userChange.id,
              name: userChange.name,
              password: userChange.password,
              time_start: user.time_start,
              time_end: user.time_end
            })
            that.setData({
              userInfo: that.data.userInfo
            })
            wx.setStorage({
              key: 'userInfo',
              data: that.data.userInfo,
              success () {
                wx.getStorage({
                  key: 'userInfo',
                  success(res){
                    console.log('[manager] 存储用户数据:')
                    console.log(res.data)
                  }
                })
              },
              fail() {
                console.log('[manager] 存储用户数据失败！')
              }
            })
          } else {
            that.data.userRequestReply.push({
              id: user.id,
              time_start: user.time_start,
              time_end: user.time_end,
              reply: false
            })
          }
          wx.setStorage({
            key: 'userRequestReply',
            data: that.data.userRequestReply,
            success () {
              wx.getStorage({
                key: 'userRequestReply',
                success(res){
                  console.log('[manager] 存储用户申请回复:')
                  console.log(res.data)
                }
              })
            },
            fail() {
              console.log('[manager] 存储用户申请回复失败！')
            }
          })
        }
      })
      wx.setStorage({
        key: 'userRequest',
        data: this.data.userRequest,
        success () {
          wx.getStorage({
            key: 'userRequest',
            success(res){
              console.log('[manager] 存储用户申请:')
              console.log(res.data)
            }
          })
        },
        fail() {
          console.log('[manager] 存储用户申请失败！')
        }
      })
    }
  },
  onShow: function() {
    let that = this
    wx.getStorage({
      key: 'userInfo',
      success(res) {
        if(res.data != undefined) {
          console.log('[manager] 获得用户数据:')
          console.log(res.data)
          that.setData({
            userInfo: wx.getStorageSync('userInfo')
          })
        }
      },
      fail() {
        console.log('[manager] 获得用户数据失败!')
      }
    })
    wx.getStorage({
      key: 'userRequest',
      success(res) {
        if(res.data != undefined) {
          console.log('[manager] 获得用户申请:')
          console.log(res.data)
          that.setData({
            userRequest: wx.getStorageSync('userRequest')
          })
        }
        if(that.data.isLogin) {
          that.checkUserRequest()
        }
      },
      fail() {
        console.log('[manager] 获得用户申请失败!')
      }
    })
    wx.getStorage({
      key: 'userRequestReply',
      success(res) {
        if(res.data != undefined) {
          console.log('[manager] 获得用户申请回复:')
          console.log(res.data)
          that.setData({
            userRequestReply: wx.getStorageSync('userRequestReply')
          })
        }
      },
      fail() {
        console.log('[manager] 获得用户申请回复失败!')
      }
    })
  },
  onUnload: function() {
    if(this.data.isLogin) {
      this.setData({isLogin: false});
      this.mqttSend(this.data.mqtt.topic_log, '管理员已下线')
    }
  },
  bindInputName: function(e) {
    this.data.input.name = e.detail.value
    this.setData({input: this.data.input})
  },
  bindInputID: function(e) {
    this.data.input.id = e.detail.value
    this.setData({input: this.data.input})
  },
  bindInputPassword: function(e) {
    this.data.input.password = e.detail.value
    this.setData({input: this.data.input})
  },
  bindInputPasswordCheck: function(e) {
    this.data.input.passwordCheck = e.detail.value
    this.setData({input: this.data.input})
  },
  bindChangeTimeStart: function(e) {
    this.data.input.time_start = e.detail.value
    this.setData({input: this.data.input})
  },
  bindChangeTimeEnd: function(e) {
    this.data.input.time_end = e.detail.value
    this.setData({input: this.data.input})
  },
  bindButtonLoginTap: function() {
    if (this.data.input.id == undefined) {
      wx.showToast({
        title: '请输入账号',
        icon: 'error',
        duration: 2000
      })
    } else if (this.data.input.password == undefined) {
      wx.showToast({
        title: '请输入密码',
        icon: 'error',
        duration: 2000
      })
    } else if (this.data.input.id != "admin") {
      wx.showToast({
        title: '账号不存在',
        icon: 'error',
        duration: 2000
      })
    } else if (this.data.input.password != "admin") {
      wx.showToast({
        title: '密码错误',
        icon: 'error',
        duration: 2000
      })
    } else {
      this.data.input.id = undefined
      this.data.input.password = undefined
      this.setData({
        isLogin: true,
        input: this.data.input
      })
      this.mqttSend(this.data.mqtt.topic_log, '管理员已登录')
      this.checkUserRequest()
    }
  },
  bindButtonRegisterTap: function() {
    if(this.data.input.name == undefined || this.data.input.name == "") {
      wx.showToast({
        title: '请输入姓名',
        icon: 'error',
        duration: 2000
      })
    } else if(this.data.input.id == undefined) {
      wx.showToast({
        title: '请输入用户ID',
        icon: 'error',
        duration: 2000
      })
    } else if(this.data.input.password == undefined) {
      wx.showToast({
        title: '请设置用户密码',
        icon: 'error',
        duration: 2000
      })
    } else if(this.data.input.password != this.data.input.passwordCheck) {
      wx.showToast({
        title: '密码不一致',
        icon: 'error',
        duration: 2000
      })
    } else {
      let index = this.data.userInfo.findIndex(item => item.id == this.data.input.id)
      if(index >= 0) {
        console.log('[manager] 删除冗余的用户数据:')
        console.log(this.data.userInfo.splice(index, 1))
      }
      this.data.userInfo.push({
        id: this.data.input.id,
        name: this.data.input.name,
        password: this.data.input.password,
        time_start: this.data.input.time_start,
        time_end: this.data.input.time_end
      })
      this.setData({userInfo: this.data.userInfo})
      let that = this
      wx.setStorage({
        key: 'userInfo',
        data: that.data.userInfo,
        success () {
          wx.getStorage({
            key: 'userInfo',
            success(res){
              console.log('[manager] 存储用户数据:')
              console.log(res.data)
            }
          })
        },
      })
      console.log('[manager] 注册用户:')
      console.log(this.data.userInfo.find(item => item.id == this.data.input.id))
      wx.showToast({
        title: '注册成功',
        icon: 'success',
        duration: 2000
      })
    }
  },
  bindButtonDeleteAllUserTap: function() {
    console.log('[manager] 删除所有用户数据:')
    this.setData({userInfo: []})
    this.mqttSend(this.data.mqtt.topic_cmd, {cmd: "delete"})
    let that = this
    wx.setStorage({
      key: 'userInfo',
      data: that.data.userInfo,
      success () {
        wx.getStorage({
          key: 'userInfo',
          success(res){
            console.log('[manager] 存储用户数据:')
            console.log(res.data)
          }
        })
      },
      fail() {
        console.log('[manager] 存储用户数据失败！')
      }
    })
  }
})